import { login, logout, getInfo } from '@/api/user';
import { getToken, setToken, removeToken } from '@/utils/auth';

const state = {
  token: getToken(),
  user: null
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USER: (state, user) => {
    state.user = user;
  }
};

const actions = {
  // 登陆
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(res => {
          res = res.data;
          console.log('登陆返回', res);
          if (res.code !== 200) {
            reject(res);
            return;
          }
          const token = res.data.token;
          commit('SET_TOKEN', token);
          setToken(token);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const data = response.data.data.userMessage;
          console.log('获取个人信息', data);
          commit('SET_USER', data);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 退出登陆
  logout() {
    return new Promise((resolve, reject) => {
      logout()
        .then(res => {
          console.log('退出登陆', res);
          if (res.data.code === 200) {
            removeToken();
            window.location.reload();
            resolve();
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
